<template>
  <el-card>
    <el-form
      ref="formRef"
      :rules="rules"
      label-position="left"
      label-width="100px"
      :model="registerUser"
      style="max-width: 460px"
      status-icon
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="registerUser.name" />
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input v-model="registerUser.pass" type="password" />
      </el-form-item>
      <el-form-item label="重复密码" prop="rePass">
        <el-input v-model="registerUser.rePass" type="password" />
      </el-form-item>
      <el-form-item @click="refreshCode()">
        <el-image style="width: 200px" :src="captcha" fit="contain"></el-image>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input
          v-model="registerUser.code"
          @keyup.enter="doRegister(formRef)"
        />
      </el-form-item>
    </el-form>
    <div class="bt-login">
      <el-button type="primary" @click="doRegister(formRef)">注册</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { onMounted } from "vue";
import { baseURL } from "../../config/axios.config";
import { register } from "../../api/userAPI";
import { useRouter } from "vue-router";

const formRef = ref();
const captcha = ref("");
const t = ref("");
const router = useRouter();
const registerUser = reactive({
  name: "",
  pass: "",
  rePass: "",
  code: "",
});
const rules = reactive({
  name: [
    { required: true, message: "请输入 用户名", trigger: "blur" },
    {
      min: 4,
      max: 18,
      message: "用户名至少是 4 位数, 最多 18 位数",
      trigger: "blur",
    },
  ],
  pass: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 4, max: 18, message: "密码至少是 4 位数", trigger: "blur" },
  ],
  rePass: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再输入一次密码"));
        } else if (value !== registerUser.pass) {
          callback(new Error("两次密码输入不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});
const doRegister = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      register(registerUser, t.value)
        .then((data) => {
          ElMessage.success(data.message);
          router.push("/login");
        })
        .catch(() => {
          // 登录异常一般是 验证码错误, 所以这里刷新下验证码
          refreshCode();
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const refreshCode = () => {
  t.value = Math.random();
  captcha.value = `${baseURL}/captcha?t=${t.value}`;
};
onMounted(refreshCode);
</script>

<style scoped>
.bt-login {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
